package com.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.mapper.EmployeeRoleMapper;
import com.community.mapper.RoleMapper;
import com.community.pojo.EmployeeRole;
import com.community.pojo.Role;
import com.community.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author TangHaoSong Fly ChenJie HeYuHang
 * @since 2024-05-15
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private EmployeeRoleMapper employeeRoleMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Role> getRoleByEmployeeId(Integer employeeId) {
        // 构建查询条件，根据员工ID查询员工角色关联表中的记录
        QueryWrapper<EmployeeRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("employee_id", employeeId);

        // 查询员工角色关联表中的记录
        List<EmployeeRole> employeeRoles = employeeRoleMapper.selectList(queryWrapper);

        // 创建角色集合
        List<Role> roles = new ArrayList<>();

        // 遍历员工角色关联表中的记录，获取对应的角色信息
        for (EmployeeRole employeeRole : employeeRoles) {
            Integer roleId = employeeRole.getRoleId();

            // 根据角色ID查询角色信息，并且is_delete为0
            Role role = roleMapper.selectOne(new QueryWrapper<Role>().eq("id", roleId).eq("is_delete", 0));

            if (role != null) {
                // 如果角色信息不为空，则将其加入角色列表
                roles.add(role);
            }
        }

        // 返回角色列表
        return roles;
    }
}
